<?php

namespace App\Http\Controllers;

use App\Login;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    /**
     * 登录及注册
     *
     * @param  Request
     * @return Response
     */
    public function login(Request $request)
    {
        try{
            $code = $request->input('code', '');
            $inviterId = $request->input('inviterId', '');
            if(empty($code)){
                return response()->json(['success'=>false,'code'=>5001,'message'=>'必填参数不能为空']);
            }
            //通过code获取openid
            $openInfo = json_decode(self::httpGet('https://api.weixin.qq.com/sns/jscode2session?appid='.env('APP_ID').'&secret='.env('APP_SECRET').'&js_code='.$code.'&grant_type=authorization_code'));
//            print_r($openInfo);exit;
            if(isset($openInfo->errcode)){
                return response()->json(['success'=>false,'code'=>$openInfo->errcode,'message'=>$openInfo->errmsg]);
            }
            $openId = $openInfo->openid;
            $sessionkey = $openInfo->session_key;
//            $openId = $request->input('code', '');
//            $sessionkey = $request->input('code', '');
            //判断是否存在，如果存在返回登录信息，反之注册
            $info = DB::table('users')->where('open_id','=',$openId)->first();
            if($info){
                //判断今天是否已经登录过
                $startTime = strtotime(date("Y-m-d")." 00:00:00");
                $endTime = strtotime(date("Y-m-d")." 23:59:59");
                $isLogin = DB::table('diamond_use')->where([['users_id','=',$info->id],['diamond_type','=',3]])
                    ->whereBetween('create_time',[$startTime,$endTime])->value('id');
                if($isLogin){
                    return response()->json(['success'=>true,'code'=>1000,'message'=>$info]);
                }
                //加登录钻石
                DB::beginTransaction();
                if($info->today_login_diamonds !== '0.00'){
                    $saveData['diamonds'] = floatval($info->diamonds)+floatval($info->today_login_diamonds);
                    $saveData['last_login_time'] = time();
                    $update = DB::table('users')->where('id','=',$info->id)->update($saveData);
                    $insert = DB::table('diamond_use')->insert(array('users_id'=>$info->id,'diamond'=>$info->today_login_diamonds,'diamond_type'=>3,'create_time'=>time()));
                }else{
                    $update = true;
                    $insert = true;
                }
                //加入登录信息及token
                $token = DB::table('login_token')->where('users_id','=',$info->id)->value('id');
                if($token){
                    $saveToken = DB::table('login_token')->where('users_id','=',$info->id)->update(array('session_key'=>$sessionkey,"time"=>time()));
                }else{
                    $saveToken = DB::table('login_token')->insert(array("users_id"=>$info->id,'session_key'=>$sessionkey,"time"=>time()));
                }
                if($update && $insert && $saveToken){
                    DB::commit();
                    //发送每日登录消息
                    if($info->today_login_diamonds !== '0.00'){
                        if(self::SendTemplate($info->id,3,'【每⽇登陆】钻⽯奖励',$info->today_login_diamonds.'💎','每⽇登陆：钻⽯已经到账，试试使⽤钻⽯让朋友帮你找货吧',date("m-d H:i")) == 1004){
                            self::SendTemplate($info->id,3,'【每⽇登陆】钻⽯奖励',$info->today_login_diamonds.'💎','每⽇登陆：钻⽯已经到账，试试使⽤钻⽯让朋友帮你找货吧',date("m-d H:i"));
                        }
                    }
                    return response()->json(['success'=>true,'code'=>1000,'message'=>$info]);
                }else{
                    DB::rollBack();
                    return response()->json(['success'=>false,'code'=>5003,'message'=>'登录失败']);
                }
            }else{
                //注册，判断是否有邀请人，存在判断邀请人上是否还有邀请人，判断加钻石
                $data['open_id'] = $openId;
                $data['u_id'] = mt_rand(10000000,99999999).mt_rand(100,999);
                $data['create_time'] = time();
                $setting = DB::table('diamond_setting')->first();
                $inviterAddDiamond = true;
                $inviterUseDiamond = true;
                $binviterAddDiamond = true;
                $binviterUseDiamond = true;
                DB::beginTransaction();
                if(!empty($inviterId)){
                    //邀请人加钻石及钻石记录
                    $inviterAddDiamond = DB::table('users')->where('id','=',$inviterId)->increment('diamonds', $setting->invite_new_users);
                    $inviterUseDiamond = DB::table('diamond_use')->insert(array('users_id'=>$inviterId,'diamond'=>$setting->invite_new_users,'diamond_type'=>8,'create_time'=>time()));
                    //判断邀请人是否存在邀请人
                    $binviterId = DB::table('users')->where('id','=',$inviterId)->value('inviter_id');
                    if($binviterId){
                        //给邀请人加钻石
                        $binviterAddDiamond = DB::table('users')->where('id','=',$binviterId)->increment('diamonds', $setting->invite_new_new_users);
                        $binviterUseDiamond = DB::table('diamond_use')->insert(array('users_id'=>$binviterId,'diamond'=>$setting->invite_new_new_users,'diamond_type'=>9,'create_time'=>time()));
                    }
                }
                //继续注册
                $data['diamonds'] = $setting->register;
                $data['inviter_id'] = $inviterId;
                $register = DB::table('users')->insertGetId($data);
                //添加注册钻石获取记录
                $useDiamond = DB::table('diamond_use')->insert(array('users_id'=>$register,'diamond'=>$setting->register,'diamond_type'=>1,'create_time'=>time()));
                //加入登录信息及token
                $saveToken = DB::table('login_token')->insert(array("users_id"=>$register,"time"=>time()));
                if($register && $useDiamond && $inviterAddDiamond && $inviterUseDiamond && $binviterAddDiamond && $binviterUseDiamond && $saveToken){
                    DB::commit();
                    $info = DB::table('users')->where('id','=',$register)->first();
                    return response()->json(['success'=>true,'code'=>1000,'message'=>$info]);
                }else{
                    DB::rollBack();
                    return response()->json(['success'=>false,'code'=>5004,'message'=>'注册失败']);
                }
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    public function httpGet($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }
}
